#coding:utf-8
import time
import urllib2
import threading
from Queue import Queue
from time import sleep

# 性能测试页面
PERF_TEST_URL = "http://localhost:80/~foRK/index.html"

# 配置:压力测试
#THREAD_NUM = 10			# 并发线程总数
#ONE_WORKER_NUM = 500		# 每个线程的循环次数
#LOOP_SLEEP = 0.01		# 每次请求时间间隔(秒)

# 配置:模拟运行状态
THREAD_NUM = 5		# 并发线程总数
ONE_WORKER_NUM = 10		# 每个线程的循环次数
LOOP_SLEEP = 0.5		# 每次请求时间间隔(秒)

# 出错数
ERROR_NUM = 0

#具体的处理函数，负责处理单个任务
def doWork(index):
	t = threading.currentThread()
	#print "["+t.name+" "+str(index)+"] "+PERF_TEST_URL

	try:
		html = urllib2.urlopen(PERF_TEST_URL).read()
	except urllib2.URLError, e:
		print "["+t.name+" "+str(index)+"] "
		print e
		global ERROR_NUM
		ERROR_NUM += 1

#这个是工作进程，负责不断从队列取数据并处理
def working():
	t = threading.currentThread()
	print "["+t.name+"] Sub Thread Begin"

	i = 0
	while i < ONE_WORKER_NUM:
		i += 1
		doWork(i)
		sleep(LOOP_SLEEP)

	print "["+t.name+"] Sub Thread End"


def main():
	#doWork(0)
	#return
	
	t1 = time.time() #开始时间

	Threads = []

	# 创建线程
	for i in range(THREAD_NUM): #线程数,THREAD_NUM=5,i=0,1,2,3,4
		t = threading.Thread(target=working, name="T"+str(i))
		#target 是被 run()方法调用的回调对象. 默认应为None, 意味着没有对象被调用
		#name 为线程名字
		t.setDaemon(True)  #设置子线程是否随主线程一起结束,默认为flase
		Threads.append(t)  #把t0,t1,t2,t3,t4放入列表

	#启动所有线程
	for t in Threads:
		t.start()

	# 主线程中等待所有子线程退出
	for t in Threads:
		t.join()

	print "main thread end"

	t2 = time.time()  #线程结束时间
	#状态输出
	print "========================================"
	print "URL:", PERF_TEST_URL
	print "Concurrency:", THREAD_NUM, "*", ONE_WORKER_NUM, "=", THREAD_NUM*ONE_WORKER_NUM
	print "All_Time(S):", t2-t1
	print "One_Time(S):", (t2-t1) / (THREAD_NUM*ONE_WORKER_NUM)
	print "Second_Requests:", 1 / ((t2-t1) / (THREAD_NUM*ONE_WORKER_NUM))
	print "Error:", ERROR_NUM


if __name__ == "__main__": main()
